let express = require('express');
let mysql = require('./db');
const jwt = require('jsonwebtoken');

const auth = require('./auth');// 引入jwt token工具
let {key,expir} = auth
let router = express.Router();
let token = jwt.sign({user:'quxuenoodle'},key,{expiresIn:expir})


//普通用户登录
router.get('/_login', (req, res) => {
    let { username, password } = req.query;
    // 登录：获取前端传递的用户名和密码
    // 那这个用户名和密码去书数据库中匹配是否存在该数据
    // 用户名和密码 就是我们查询数据条件
    mysql.query(`select * from test_user where username='${username}' and password='${password}';`, (state, data) => {
        if (state) {
            
            if (data.length == 0) {
                var msg = '用户名或密码错误';
                var code = 400;
            } else {
                data[0].authorization = token 
                var msg = '登录成功'
                var code = 200;
            }

            res.send({
                code,
                msg: msg,
                data
            })

        } else {
            res.send({
                code: 400,
                msg: 'error',
                data
            })
        }
    })
})

//注册时检查用户名是否可用
router.get('/regname', (req, res) => {
    let { username } = req.query;
    // 登录：获取前端传递的用户名和密码
    // 那这个用户名和密码去书数据库中匹配是否存在该数据
    // 用户名和密码 就是我们查询数据条件
    mysql.query(`select * from test_user where username='${username}' ;`, (state, data) => {
        if (state) {
            if (data.length == 0) {
                var msg = '可以注册';
                var code = 200;
            } else {
                var msg = '用户名已存在'
                var code = 400;
            }
            res.send({
                code,
                msg: msg,
                data
            })

        } else {
            res.send({
                code: 400,
                msg: 'error',
                data
            })
        }
    })
})

//普通用户注册
router.post('/reg', (req, res) => {
    let { username, password,telphone } = req.body;
    // 登录：获取前端传递的用户名和密码
    // 那这个用户名和密码去书数据库中匹配是否存在该数据
    // 用户名和密码 就是我们查询数据条件
    //正则判断手机号是否符合规则
    // const telTest = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(telphone)
    //符合规则继续下一步，否则返回400
    // if (telTest) {
        console.log('手机号无误，继续注册');
        mysql.query(`insert into test_user (uid,username,password,telphone) values(Null,'${username}','${password}','${telphone}');`, (state, data) => {
            if (state) {
                res.send({
                    code: 200,
                    msg: '用户注册成功',
                    data
                })

            } else {
                res.send({
                    code: 400,
                    msg: '添加数据失败',
                    data
                })
            }
        })
    // } else {
    //     res.send({
    //         code: 400,
    //         msg: '手机号输入错误',
    //     })
    // }
})

//密码校验规则
function validatePayPassword(number) {
    //不允许全部一样的数字
    if (/^(\d)\1+$/.test(number)) return false
    let str = number.replace(/\d/g, function ($0, pos) {
        return parseInt($0) - pos
    })
    if (/^(\d)\1+$/.test(str)) return false

    str = number.replace(/\d/g, function ($0, pos) {
        return parseInt($0) + pos
    })
    if (/^(\d)\1+$/.test(str)) return false

    return true
}

//普通用户设置密码
router.post('/payPassword', (req, res) => {
    let { uid, paypassword } = req.body;
    //正则判断密码是否符合规则
    const payTest = validatePayPassword(paypassword)

    //符合规则继续下一步，否则返回400
    if (payTest) {
        mysql.query(`update test_user set paypassword='${paypassword}' where uid='${uid}';`, (state, data) => {
            if (state) {
                res.send({
                    code: 200,
                    msg: '用户添加密码成功',
                    data
                })
            } else {
               res.send({
                    code: 400,
                    msg: '添加密码失败',
                    data
                })
            }
        })
    } else {
        return res.send({
            code: 400,
            msg: '密码规则校验错误',
        })
    }
})

//普通用户检验支付密码
router.post('/isPay', (req, res) => {
    let { uid, paypassword } = req.body;

    mysql.query(`select * from test_user where paypassword='${paypassword}' and uid='${uid}';`, (state, data) => {
        if (state) {
            if (data.length == 0) {
                res.send({
                    code: 400,
                    msg: '用户校验密码失败',
                    data
                })
            } else {
                res.send({
                    code: 200,
                    msg: '用户校验密码成功',
                    data
                })
            }
        }
    })
})

/*管理员功能 */

//管理员用户登录
router.get('/admin_login', (req, res) => {
    let { username, password } = req.query;
    // 登录：获取前端传递的用户名和密码
    // 那这个用户名和密码去书数据库中匹配是否存在该数据
    // 用户名和密码 就是我们查询数据条件
    mysql.query(`select * from admin_user where username='${username}' and password='${password}';`, (state, data) => {
        if (state) {
            
            if (data.length == 0) {
                var msg = '用户名或密码错误';
                var code = 400;
            } else {
                data[0].authorization = token 
                var msg = '登录成功'
                var code = 200;
                
            }
            res.send({
                code,
                msg: msg,
                data,
            })

        } else {
            res.send({
                code: 400,
                msg: 'error',
                data
            })
        }
    })
})

// 删除用户
router.post('/deluser', (req, res) => {
    let { uid } = req.body;
    // console.log(req.body);
    mysql.query(`delete from test_user where uid = '${uid}';`, (state, data) => {
        if (state) {
            if (data.length == 0) {
                res.send({
                    code: 300,
                    msg: '用户名不存在',
                    data
                })
            } else {
                res.send({
                    code: 200,
                    msg: '删除成功',
                    data
                })
            }
        } else {
            res.send({
                code: 400,
                msg: '请求错误',
                data
            })
        }
    })
})

// 查询所有用户
router.get('/selAlluser', (req, res) => {
    let { page, size } = req.query
    // 当不传递 page 和 limit 需要设置默认值
    page = page || 1;
    size = size || 10;
    let index = (page - 1) * size;
    mysql.query(`select * from test_user limit ${index},${size};`, (state, data) => {
        if (state) {
            mysql.query(`select count(*) as total from test_user;`,(state1,total)=>{
                if (state1) { 
                        res.send({
                            code: 200,
                            msg: '请求成功',
                            total: total[0].total,
                            data
                        })
                } else {
                    res.send({
                        code: 400,
                        msg: '请求错误',
                        data
                    })
                }
            })
        } else {
            res.send({
                code: 400,
                msg: '请求错误',
                data
            })
        }
    })
})

// 查询单个用户
router.get('/:uid',(req, res)=>{
    let {uid} = req.query
    mysql.query(`select * from test_user where uid='${uid}';`,(state, data) => {
        if (state) { 
                res.send({
                    code: 200,
                    msg: '请求成功',
                    data:data[0]
                })
        } else {
            res.send({
                code: 400,
                msg: '请求错误',
                data
            })
        }
    })
})

//批量删除用户
router.post('/delUsers', function(req, res){
    let {ids} = req.body
    // let dishes_ids =  ids.join(',')
    mysql.query(`delete from test_user where uid in (${ids});`,(state, data)=>{
        if (state) {
            res.send({
                code:200,
                msg: '用户移除成功',
                data
            })

        } else {
            res.send({
                code: 400,
                msg: '用户移除失败',
                data
            })
        }
    })
})

//修改用户
router.post('/updateUsers', function(req, res){
    let {uid,username,password,telphone} = req.body

    console.log('uid'+uid);

    mysql.query(`update test_user set username='${username}', password='${password}' ,telphone='${telphone}' where uid='${uid}';`,(state, data)=>{
        if (state) {
            res.send({
                code:200,
                msg: '用户修改成功',
                data
            })

        } else {
            res.send({
                code: 400,
                msg: '用户修改失败',
                data
            })
        }
    })
})
//添加用户
// router.post('/adduser', (req, res) => {
//     let { username, age,sex,telphone } = req.body;
//     mysql.query(`insert into test_user (id,username,telphone) values(NULL, '${username}', '${age}','${sex}', '${telphone}');`, (state, data) => {
//         if (state) {
//             console.log(data);
//             res.send({
//                 code: 200,
//                 msg: '添加数据成功',
//                 data
//             })
//         } else {
//             res.send({
//                 code: 400,
//                 msg: '添加数据失败',
//                 data
//             })
//         }
//     })
// })

module.exports = router